/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.sober.criteria.expression;

import com.jspx.sober.TableModels;
import com.jspx.sober.criteria.projection.Criterion;
import com.jspx.sober.util.SoberUtil;
import com.jspx.utils.ArrayUtil;
import com.jspx.utils.StringUtil;
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;

/**
 * Created by IntelliJ IDEA.
 * User:chenYuan (mail:39793751@qq.com)
 * Date: 2007-1-8
 * Time: 11:19:11
 */
public class InExpression implements Criterion {
    private String propertyName;
    private Set<Object> values = new HashSet<Object>();

    public InExpression(String propertyName, Object[] values) {
        this.propertyName = propertyName;
        if (!ArrayUtil.isEmpty(values))
            this.values.addAll(Arrays.asList(values));
    }

    public Object[] getParameter(TableModels soberTable) {
        return values.toArray();
    }

    public String toSqlString(TableModels soberTable,String databaseName) {
        StringBuilder sb = new StringBuilder();
        if (values!=null)
        for (int i = 0; i < values.size(); i++) {
            sb.append("?");
            if (i != values.size() - 1) {
                sb.append(",");
            }
        }
        if (!StringUtil.hasLength(sb.toString())) {
            return propertyName + " IN ('')";
        }
        return propertyName + " IN (" + sb.toString() + ") ";
    }

    public String toString()
    {
        if (values==null) return propertyName + " IN ('')";
        Object[] objects = values.toArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < objects.length; i++) {
            sb.append(SoberUtil.toTypeString(objects[i]));
            if (i != values.size() - 1) {
                sb.append(",");
            }
        }
        if (!StringUtil.hasLength(sb.toString())) {
            return propertyName + " IN ('')";
        }
        return propertyName + " IN (" + sb.toString() + ") ";
    }

    public String[] getFields()
    {
        return new String[]{propertyName};
    }

    public String termString()
    {
        return toString();
    }
}